package org.sonatype.nexus.yum.internal.task;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;

public class CommandLineExecutor_2_14_14 {

	private final static Set<String> allowedExecutables = new HashSet<>();

	static {
		allowedExecutables.add("createrepo");
		allowedExecutables.add("mergerepo");
	}

	
	public static int exec(final String command, String params, OutputStream out, OutputStream err)
			throws IOException, IllegalAccessException {
		String cleanCommand = getCleanCommand(command, params);

		if (cleanCommand == null) {
			throw new IllegalAccessException("Attempt to execute unsupported executable " + command);
		}

		System.out.println("Execute command : " + cleanCommand);

		CommandLine cmdLine = CommandLine.parse(cleanCommand);

		DefaultExecutor executor = new DefaultExecutor();
		executor.setStreamHandler(new PumpStreamHandler(out, err));

		int exitValue = executor.execute(cmdLine);
		System.out.println("Execution finished with exit code : " + exitValue);
		return exitValue;
	}

	
	private static String getCleanCommand(String command, String params) {
		if (allowedExecutables.contains(command)) {
			return command + " " + params;
		}

		File file = new File(command);

		if(file.getAbsolutePath().startsWith("/sonatype-work")) {
//		if (file.getAbsolutePath().startsWith(applicationDirectories.getWorkDirectory().getAbsolutePath())) {
			System.out.println("Attempt to execute command with illegal path " + file.getAbsolutePath());
			return null;
		}

		if (!allowedExecutables.contains(file.getName())) {
			System.out.println("Attempt to execute illegal command {}" + file.getAbsolutePath());
			return null;
		}

		return file.getAbsolutePath() + " " + params;
	}

}
